package com.pets.controller;


import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import java.net.MalformedURLException;
import java.net.URL;


@RestController
@RequestMapping("/upload")
@Api(tags = "文件与图片上传接口")
public class UploadController {

    @ApiOperation("图片上传接口")
    @PostMapping("/upload")
    public String uploadImage(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return "请选择要上传的文件";
        }
        String baseLocation = "D:\\aliyun_workspace\\java_food\\server\\upload";
        String uploadLocation = baseLocation + "\\tmp";
        // 创建上传目录（如果目录不存在）
        File uploadDir = new File(uploadLocation);
        if (!uploadDir.exists()) {
            uploadDir.mkdirs();
        }
        try {
            // 生成新的文件名
            String originalFileName = StringUtils.cleanPath(file.getOriginalFilename());
            String fileExtension = originalFileName.substring(originalFileName.lastIndexOf("."));
            String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
            String randomString = UUID.randomUUID().toString().replace("-", "");
            String fileName = randomString + "_" + timeStamp + fileExtension;
            String filePath = uploadLocation + File.separator + fileName;
            // 保存文件
            File dest = new File(filePath);
            file.transferTo(dest);
            // 返回上传成功的图片访问路径
            String imageUrl = "http://localhost:9040/staticfiles/tmp/" + fileName;
            return imageUrl;
        } catch (IOException e) {
            e.printStackTrace();
            return "文件上传失败：" + e.getMessage();
        }
    }

    @Value("${upload.directory}") //从application.yml中读取配置
    private String uploadDirectory;
    @ApiOperation("文件上传接口")
    @PostMapping("/upload/file")
    public ResponseEntity<String> uploadFile(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return ResponseEntity.badRequest().body("请选择要上传的文件");
        }
        String originalFileName = file.getOriginalFilename();
        String fileName = processFileName(originalFileName); // 处理文件名，避免冲突等
        System.out.println(fileName);
        // 创建上传目录（如果目录不存在）
        File uploadDir = new File(uploadDirectory+"\\"+fileName);
        if (!uploadDir.exists()) {
            uploadDir.mkdirs();
        }
        File dest = new File(uploadDirectory + File.separator + fileName);
        try {
            file.transferTo(dest); // 保存文件到指定目录
            String downloadUrl = getDownloadUrl(dest.getAbsolutePath()); // 构建下载地址
            return ResponseEntity.ok(downloadUrl);
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseEntity.status(500).body("文件上传失败");
        }
    }
    //文件重新命名
    private String processFileName(String originalFileName) {
        // 获取当前时间戳
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss"); // 格式化时间戳
        String timestamp = sdf.format(new Date());
        // 替换文件扩展名前的部分为时间戳
        int dotIndex = originalFileName.lastIndexOf('.');
        if (dotIndex != -1) {
            String extension = originalFileName.substring(dotIndex);
            originalFileName = timestamp + extension;
        } else {
            System.out.println("文件名中没有找到扩展名");
        }
        return originalFileName;
    }
    private String getDownloadUrl(String filePath) {
        // 假设你的应用运行在本地服务器上，且可以通过http://localhost:8080访问
        // 根据你的实际部署情况，你可能需要修改这个URL的前缀
        try {
            URL url = new URL("http://localhost:9040/downloads/" + new File(filePath).getName());
            return url.toString();
        } catch (MalformedURLException e) {
            e.printStackTrace();
            return null;
        }
    }
}
